<template>
	<view>
		<st-mc-framework :navTitle="ModuleTitle" @changeLevel="changeLevel" ref="framework"
			@AddModuleData_select='AddModuleData_select'>
			<template #content>
				<view class="content" style="width: 100%;height: 100%;">
					<view class="contentBox" style="flex: 1;">
						<view class="container">

							<u--form class="u_form" labelPosition="left" :model="baseFormData" ref="uForm">

								<u-row justify="start" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="单据编号:">
											<u--input v-model="baseFormData.BillNO" placeholder="自动生成单据编号" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="单据日期:">
											<u--input v-model="baseFormData.BillDate" placeholder="自动生成单据日期" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="产品名称:">
											<u--input v-model="baseFormData.ProductName" placeholder="产品名称" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>

								</u-row>
								<u-row justify="start" gutter="20">

									<u-col span="4">
										<u-form-item labelWidth="auto" label="派工单号:">
											<u--input v-model="baseFormData.PGDBillNO" placeholder="派工单号" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="申请人:">
											<u--input v-model="baseFormData.EmplName" placeholder="自动带出申请人" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="申请部门:">
											<u--input v-model="baseFormData.ClassName" placeholder="申请部门" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>

								</u-row>
								<u-row justify="space-between" gutter="20">

									<u-col span="12">
										<u-form-item labelWidth="auto" label="异常原因:" required>
											<u--input v-model="baseFormData.NGCause" placeholder="请输入异常原因"
												border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>

								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="审核人:">
											<u--input v-model="baseFormData.Approver" placeholder="审核人" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="审批状态:">
											<u--input v-model="baseFormData.ApproveStatus" placeholder="审批状态" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="审批时间:">
											<u--input v-model="baseFormData.ApproveTime" placeholder="审批时间" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>
								<u-row justify="space-between" gutter="20">
									<u-col span="12">
										<u-form-item labelWidth="auto" label="审核意见:">
											<u--input v-model="baseFormData.ApproveContent" placeholder="请输入审核意见"
												border="none"></u--input>
										</u-form-item>
									</u-col>

								</u-row>
								<u-row justify="space-between" gutter="20">
									<u-col span="12">
										<u-form-item labelWidth="auto" label="现场照片:">
											<u-upload :fileList="DImgs" @afterRead="afterRead" @delete="deletePic"
												multiple :maxCount="5" :previewFullImage="true"></u-upload>
										</u-form-item>
									</u-col>
								</u-row>



							</u--form>

						</view>

					</view>

					<view class="DetailsbottomBtns">
						<button class="button1" block @click="SubmitBtn('保存')" style="z-index: 99;">
							{{changeButton}}
						</button>
						<button class="button2" :class="baseFormData.Approve ? 'approved' : 'pending'" block
							@click="ToExamine" v-show="ToExamineShow">
							{{ToExamineName}}
						</button>
					</view>
				</view>
			</template>
		</st-mc-framework>
		<u-action-sheet :actions="FaultNameList" :show="FaultNameShow" @select="FaultNameClick"
			@close="FaultNameShow=false"></u-action-sheet>
		<u-toast ref="uToast"></u-toast>
		<u-action-sheet :actions="FaultTypeNameList" :show="FaultTypeNameShow" @select="FaultTypeNameClick"
			@close="FaultTypeNameShow=false"></u-action-sheet>
		<u-toast ref="uToast"></u-toast>

		<u-modal :show="modalshow" :title="modaltitle" width="400" @confirm='modalconfirm'>
			<view class="slot-content">
				{{modalcontent}}
			</view>
		</u-modal>
		<m-loading :text="loadingName" v-model="showMLoading" :showClose="false"
			maskBackgroundColor="rgba(0,0,0,0.3)"></m-loading>
	</view>
</template>


<script>
	import {
		getTimeStamp,
		getFormatDateTime,
		getBefore7DateTime,
		formatDateTime,
		navigateMixin,
		baseAddModuleData_select,
		getchangeLevel
	} from '@/st_mes_zs/common/base.js';

	export default {
		mixins: [navigateMixin, baseAddModuleData_select],
		data() {
			return {

				DImgs: [],
				serverIP: '',
				FaultTypeNameShow: false,
				FaultTypeNameList: [],
				FaultNameShow: false,
				FaultNameList: [],

				baseFormData: {
					ReviewID: 0,
					PGDBillNO: '',
					NGCause: '',
					ProductID: null,
					ProductName: '',
					InspectionID: null,
					EmplID: null,
					EmplName: '',
					EquipmentName: '',
					EquipmentCode: '',
					EquipmentID: '',
					PGBillNo: '',
					Approve: false,
					ApproveStatus: '',
					Approver: '',
					ApproveContent: '',
					ApproveTime: ''
				},

				DImgs: [],
				sexs: [{
					text: '合格',
					value: 0
				}, {
					text: '不合格',
					value: 1
				}],
				ToExamineShow: false,
				ToExamineName: '审核',
				changeName: '',
				changeButton: '保存',
				modalshow: false,
				modaltitle: '提示',
				modalcontent: '',
				FWorkshopID: null, //模块id
				ModuleTitle: '', //标题
				showMLoading: false,
				loadingName: '正在加载中……',
			};
		},
		onReady() {
			var that = this
			uni.hideLoading();
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = that.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			that.FWorkshopID = MesBasicInfo.FWorkshopID;
			that.ModuleTitle = appConfigInfo.ActiveModule.ModuleName;
			that.$nextTick(() => {
				setTimeout(() => {
					that.BtnShow = true;
				}, 500)
			})
		},
		onLoad(onLoad) {
			var that = this
			that.$safeStatus({
				payload: '其他', // 要传递的数据
			});
			// 缓存状态引用
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = this.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			// 统一处理加载状态
			const setLoading = (state) => this.showMLoading = state;
			// 主处理逻辑
			if (onLoad.ReviewID) {
				setLoading(true);
				this.queryList(onLoad.ReviewID)
				return;
			}
			if (onLoad.Detailsitem) {
				var formDefaults = JSON.parse(onLoad.Detailsitem)
				that.Request.request('getEmplByJobName', {
					EmplID: formDefaults.EmplID
				}, function(res) {
					console.log(res);
					formDefaults.ClassName = res.data.ds[0].ClassName
					console.log(formDefaults);
					that.assignFormData(that.baseFormData, formDefaults);
				})
			}
			// 统一处理表单默认值
			// var formDefaultsInfo = {
			// 	MoludID: 0,
			// 	EquipmentName: MesBasicInfo.warehouse.EquipmentName,
			// 	EquipmentCode: MesBasicInfo.warehouse.EquipmentCode,
			// 	EquipmentID: MesBasicInfo.warehouse.EquipmentID,
			// };
			// this.assignFormData(this.baseFormData, formDefaultsobj);
			setLoading(false);
		},

		onBackPress(options) { // 监听页面返回
			if (options.from == 'navigateBack') { // 通过点击路由返回
				return false;
			} else if (options.from == 'backbutton') { // 通过外置返回
				return true;
			}
		},

		onShow() {
			var that = this
			uni.$on('refreshDetail', (res) => {
				this.getValue(res.data); // 调用目标方法
			});
		},
		onUnload() {
			uni.$off('refreshDetail');
		},

		methods: {

			// 审核/取消审核
			ToExamine() {
				if (this.ToExamineName == '取消审核') {
					this.SJJ_ApproveChange(this.ToExamineName, this.baseFormData.ReviewID)
				} else {
					this.SubmitBtn(this.ToExamineName)
				}
			},
			// 审核
			SJJ_ApproveChange(str, ReviewID) {
				let that = this;
				var msg
				var Approve
				switch (str) {
					case '审核':
						Approve = 1
						msg = '审核成功'
						break;
					case '取消审核':
						Approve = 0
						msg = '撤审成功'
						break;

				}
				var obj1 = {
					ReviewID: ReviewID,
					Approve: Approve,
					ApproveContent: that.baseFormData.ApproveContent ? that.baseFormData.ApproveContent : ''
				}
				console.log(obj1);

				that.Request.request('approveCKReview', obj1, function(res) {
					that.$refs.uToast.show({
						title: '保存',
						type: 'success',
						message: msg
					})
					that.queryList(ReviewID);
				}, function(err) {
					console.log(err)
				})
			},
			// 创建表单赋值工具函数
			assignFormData(target, defaults = {}) {
				var that = this;
				Object.keys(defaults).forEach(key => {
					target[key] = defaults[key];
				});
				that.$forceUpdate();
			},
			replaceFormData(target, source, defaults = {}) {
				Object.keys(defaults).forEach(key => {
					target[key] = source[key] || defaults[key];
				});
				this.$forceUpdate()
			},
			async AddModuleData_select(res) {
				try {
					const backDelta = await this.GetModuleData_select(res);
				} catch (error) {
					console.error('返回操作失败:');
				}
			},
			modalconfirm() {
				var that = this
				that.modalshow = false
			},
			showModal(title, content) {
				this.modaltitle = title;
				this.modalcontent = content;
				this.modalshow = true;
			},

			getValue(payload) {
				var that = this;
				const {
					type,
					...data
				} = payload;
				if (payload === '返回') return;
				const typeHandlers = {
					'机台': () => ({
						EquipmentName: data.EquipmentName,
						EquipmentID: data.EquipmentID
					}),
					'模具': () => ({
						MoludID: data.MoludID,
						MoludName: data.MoludCode
					})
				};
				if (typeHandlers[type]) {
					Object.assign(this.baseFormData, typeHandlers[type]());
				}
			},
			openBaseScreen(str) {

				var that = this;
				var obj;
				if (str == '机台') {
					obj = {
						cmd: 'getEquipment',
						type: str,
						serverSearch: {
							isPaging: false, //是否分页
							// pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
							searchShow: false, //是否查询
							searchKey: 'searchKey', //搜索关键词，应包含在param中
							showText: 'EquipmentName', //查询结果显示的字段
						},
						param: {
							FWorkshopID: that.FWorkshopID,
						}
					}
				} else if (str == '模具') {
					obj = {
						cmd: 'Droplist_Molud',
						type: str,
						serverSearch: {
							isPaging: false, //是否分页
							pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
							searchShow: false, //是否查询
							searchKey: 'searchKey', //搜索关键词，应包含在param中
							showText: 'MoludCode', //查询结果显示的字段
						},
						param: {
							MoludCode: '',
						}
					}
				}

				uni.navigateTo({
					url: `../common/baseScreen?obj=${JSON.stringify(obj)}`,
					animationType: 'slide-in-right',
					animationDuration: 300
				});
			},
			GonavigateTo(obj, url) {
				let that = this;
				this.$safeNavigate({
					targetUrl: url, // 目标页面路径
					payload: obj, // 要传递的数据
				});
			},
			FaultTypeNameClick(e) {
				var that = this
				console.log(e);
				const formDefaults = {
					FaultTypeID: e.FaultTypeID,
					FaultTypeName: e.FaultTypeName
				};
				that.assignFormData(that.baseFormData, formDefaults)
				that.FaultTypeNameShow = false

			},

			addFaultTypeName() {
				var that = this
				this.Request.request('getPKGFaultType', {
					FaultTypeID: that.baseFormData.FaultTypeID
				}, (ret) => {
					if (ret.status == 200) {
						ret.data.ds.map(item => item.name = item.FaultTypeName)
						that.FaultTypeNameList = ret.data.ds
						that.FaultTypeNameShow = true

					}
				})
			},
			FaultNameClick(e) {
				var that = this
				const formDefaults = {
					FaultID: e.FaultID,
					FaultName: e.name
				};
				that.assignFormData(that.baseFormData, formDefaults)


				that.FaultNameShow = false

			},
			addFaultName() {
				var that = this
				this.Request.request('getPKGFault', {
					FaultTypeID: that.baseFormData.FaultTypeID
				}, (ret) => {
					console.log(JSON.stringify(ret));
					if (ret.status == 200) {
						ret.data.ds.map(item => item.name = item.FaultName)
						that.FaultNameList = ret.data.ds
						that.FaultNameShow = true

					}
				})
			},

			deletePic(event) {
				this.DImgs.splice(event.index, 1);
			},
			async afterRead(event) {
				let lists = [].concat(event.file)
				let fileListLen = this.DImgs.length;
				lists.map((item) => {
					this.DImgs.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})

				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.DImgs[fileListLen]
					this.DImgs.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: this.Request.IPAgreement() + this.Request.serverIP() + result
					}))
					fileListLen++
				}
			},

			uploadFilePromise(url) {
				let that = this;
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: that.Request.IPAgreement() + that.Request
							.serverIP() + '/Frame/uploadFile?dirName=' + '现场照片',
						filePath: url,
						name: 'file',
						header: {
							'Content-Type': 'multipart/form-data' // 必须设置
						},
						formData: {
							user: 'test'
						},
						success: (uploadFileRes) => {
							const data = JSON.parse(uploadFileRes.data);
							resolve(data.data)
						}
					});
				})
			},


			changebuttons(ID) {
				if (ID == 0) {
					this.changeButton = '开工'
				} else {
					this.changeButton = '保存'

				}
			},



			SubmitBtn(str) {
				var that = this;
				var BiType
				var msg
				var show = true

				if (that.baseFormData.NGCause == '' || that.baseFormData.NGCause == null) {
					msg = '请输入异常原因'
					show = false
				}

				if (show) {
					const prefix = that.Request.IPAgreement() + that.Request.serverIP();

					that.DImgs.map(obj => {
						if (typeof obj.url === 'string' && obj.url.startsWith(prefix)) {
							obj.url = obj.url.replace(prefix, '');
						}
						return obj;
					});

					var obj = {
						EquipmentID: that.baseFormData.EquipmentID,
						EmplID: that.baseFormData.EmplID,
						ProductID: that.baseFormData.ProductID,
						NGCause: that.baseFormData.NGCause,
						InspectionID: that.baseFormData.InspectionID,

						ReviewID: that.baseFormData.ReviewID ? that.baseFormData.ReviewID : 0,
						Imgs: that.DImgs.map(item => item.url).join(','),
					}

					console.log(obj);
					that.Request.request('saveCKReview', obj, function(ret) {
						console.log(ret);
						if (ret.status == 200) {
							var ReviewID = ret.data.ds[0].ReviewID
							switch (str) {
								case '保存':
									that.$refs.uToast.show({
										title: '保存',
										type: 'success',
										message: '保存成功'
									})
									setTimeout(() => {
										that.queryList(ReviewID)
									}, 1000)
									break;
								case '审核':
									that.SJJ_ApproveChange(str, ReviewID)
									break;

									// default:
									// break;
							}



						}
					})

				} else {
					that.showModal('报错', msg);

				}
			},
			queryList(id) {
				var that = this
				try {
					that.Request.request('getCKReviewDetail', {
						ReviewID: id
					}, (ret) => {
						that.showMLoading = false
						console.log(ret.data);
						const [firstItem] = ret.data.ds;
						var stringArray = firstItem.Imgs.split(',')
						if (stringArray[0] != '' && stringArray.length > 0) {
							that.DImgs = stringArray.map(item => ({
								url: that.Request.IPAgreement() + that.Request.serverIP() + item.trim()
							}));
						}
						if (firstItem.ReviewID) {
							that.ToExamineShow = true
							that.ToExamineName = firstItem.Approve == true ? '取消审核' : '审核'
							firstItem.ApproveStatus = firstItem.Approve == true ? '已审核' : '未审核'
						}
						const formDefaults = {
							...firstItem,
							BillDate: formatDateTime(firstItem.BillDate),
							ApproveTime: formatDateTime(firstItem.ApproveTime),
						};
						that.assignFormData(that.baseFormData, formDefaults)

					}, (err) => {
						that.showMLoading = false
					})
				} catch (e) {
					console.log(e)
					that.showMLoading = false
					this.$utils.hideLoading();
					this.$utils.msg('请求失败请重试')
				}
			},

			changeLevel(list, data, row) {
				getchangeLevel(data)
				uni.$emit('refreshList');
			},
		}
	}
</script>

<style lang="scss">
	@import "../css/index.css";

	.u_form .u-cell__body {
		padding: 5px 0 !important;

		.u-cell_text {
			font-weight: 600 !important;
		}
	}



	.form-item-row {
		display: flex;
		flex-wrap: wrap;

		.uni-forms-item {
			width: 46%;
			margin: 0.3% 2%;

			input {
				height: 100%;
				width: 36vw;
				border-bottom: 2px solid #51d0d0;
			}

			.uni_forms_item_view {
				width: 36vw;
			}
		}

		.uni_forms_item {
			width: 100%;
			display: flex;
			align-items: center;

			.u-upload {
				width: 85vw;
				float: right;
			}
		}


	}


	.approved {
		background-color: #FFD700 !important;

	}


	.pending {
		background-color: #dbb56a !important;
	}
</style>